﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;
using System.IO;

namespace StringSort
{
    public partial class Form1 : Form
    {
        string status = "工作状态：待添加文本";

        SQLiteConnection conn = null;
        public Form1()
        {
            InitializeComponent();

            string dbPath = "Data Source =" + Environment.CurrentDirectory + "/test.db";
            conn = new SQLiteConnection(dbPath);//创建数据库实例，指定文件位置  
            conn.Open();//打开数据库，若文件不存在会自动创建  

            string sql = "CREATE TABLE IF NOT EXISTS temporary(id integer, name TEXT(800), time TEXT(800) );";//建表语句  
            SQLiteCommand cmdCreateTable = new SQLiteCommand(sql, conn);
            cmdCreateTable.ExecuteNonQuery();//如果表不存在，创建数据表 
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label3.Text = "工作状态：开始分析文本";
            SQLiteCommand cmdInsert = new SQLiteCommand(conn);

            //清空表
            label3.Text = "工作状态：清空排序缓存";
            cmdInsert.CommandText = "delete from temporary";//清空数据
            cmdInsert.ExecuteNonQuery();
            //cmdInsert.CommandText = "update sqlite_sequence SET seq = 0 where name = 'temporary'";//自增长ID为0
            //cmdInsert.ExecuteNonQuery();

            label3.Text = "工作状态：解析字符串";
            int k = 0;
            string st = textBox1.Text;
            string[] stArr = st.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            if (stArr.Length == 0)
            {
                label3.Text = "工作状态：字符串不能为空";
                MessageBox.Show("待转化文本不能为空！");
            }

            foreach (string i in stArr)
            {
                k++;
                string[] iArr = i.Split(new string[] { "全屏会员" }, StringSplitOptions.RemoveEmptyEntries);

                if(iArr.Length <= 1)
                {
                    label3.Text = "工作状态：字符串非约定格式";
                    MessageBox.Show("非约定文本格式 ！");
                    break;
                }
                label3.Text = "工作状态：已解析数据 "+k+" 条";
                cmdInsert.CommandText = "INSERT INTO temporary VALUES("+k+", '" + i + "', '"+ iArr[1] + "')";//插入几条数据  
                cmdInsert.ExecuteNonQuery();
            }
            
            if(!label3.Text.Equals("工作状态：字符串非约定格式"))
            {
                label3.Text = "工作状态：已解析完成，共 " + k + " 条数据";
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            label3.Text = "工作状态：开始提取以解析数据";
            textBox2.Text = "";
            string ord = "asc";
            if(radioButton1.Checked == true)
            {
                ord = "desc";
            }
            string sql = "SELECT * FROM temporary order by time "+ord+";";
            SQLiteCommand cmdQ = new SQLiteCommand(sql, conn);

            SQLiteDataReader reader = cmdQ.ExecuteReader();

            label3.Text = "工作状态：数据已提取，进行排序显示";
            while (reader.Read())
            {
                textBox2.Text +=  reader.GetString(1) + "\r\n";
            }
            label3.Text = "工作状态：排序显示完成，请校验!";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            label3.Text = "工作状态：开始打开文件";
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "ir files (*.txt)|*.txt|All files (*.*)|*.*"; //过滤文件类型
            fd.InitialDirectory = Application.StartupPath + "\\Temp\\";//设定初始目录
            fd.ShowReadOnly = true; //设定文件是否只读
            DialogResult r = fd.ShowDialog();
            if (r == DialogResult.OK)
            {
                try
                {
                    Stream sr = fd.OpenFile();

                    // convert string to stream  
                    //MemoryStream stream = new MemoryStream();
                    //StreamWriter writer = new StreamWriter(stream);
                    //writer.Write(test);
                    //writer.Flush();

                    // convert stream to string  
                    //stream.Position = 0;
                    StreamReader reader;
                    if (checkBox1.Checked == true)
                    {
                        reader = new StreamReader(sr);
                    }
                    else
                    {
                        reader = new StreamReader(sr, Encoding.Default);
                    }
                    
                    string text = reader.ReadToEnd();

                    //string content = sr.ToString();
                    sr.Close();
                    textBox1.Text = text;
                    label3.Text = "工作状态：文件内容已读取到文本框";
                }
                catch
                {
                    MessageBox.Show("文件打开错误！");
                }
            }
            label3.Text = "工作状态：待分析文本";
            button1_Click(sender, e);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            label3.Text = "工作状态：保存排序文本内容至文件!";
            saveFileDialog1.Filter = "文本文件|*.txt";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                StreamWriter FileWriter = new StreamWriter(saveFileDialog1.FileName, true); //写文件

                FileWriter.Write(textBox2.Text);//将字符串写入
                FileWriter.Close(); //关闭StreamWriter对象
                MessageBox.Show("文件保存成功！");
                label3.Text = "工作状态：保存至文件已完成!";
            }
            label3.Text = "工作状态：取消排序文本内容至文件!";
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            label3.Text = "工作状态：窗体收到拖拽文件";
            string code;
            if (checkBox1.Checked == true)
            {
                code = "UTF-8";
            }
            else
            {
                code = "ANSI";
            }
            MessageBox.Show(((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString());

            string FilePath = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();

            label3.Text = "工作状态：开始读取拖拽文件";

            FileInfo fi = new FileInfo(FilePath);
            String str = fi.Extension.ToUpper();
            if (str == ".TXT")
            {

                if (checkBox1.Checked == true)
                {
                    textBox1.Text = File.ReadAllText(fi.FullName);
                }
                else
                {
                    textBox1.Text = File.ReadAllText(fi.FullName, Encoding.Default);
                }
                
                label3.Text = "工作状态：文件内容已读取到文本框";
            }
            else
            {
                MessageBox.Show("文件格式错误！");

            }
            
            label3.Text = "工作状态：待分析文本";
            button1_Click(sender, e);
        }
        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Link;
            else e.Effect = DragDropEffects.None;
        }
    }
}
